package com.lagou.config.controller;

import com.lagou.common.util.DataBaseConfig;
import com.lagou.config.pojo.Resume;
import com.lagou.config.service.ConfigServer;
import com.lagou.config.service.ResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/config")
public class ConfigController {

    @Autowired
    private ConfigServer configServer;

    @Autowired
    private ResumeService resumeService;

    @GetMapping
    public ModelAndView getConfig() throws Exception {

        DataBaseConfig config = configServer.getDataBaseConfig();
        List<Resume> resumes = resumeService.getResumes();

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("dbconfig", config);
        modelAndView.addObject("resumes", resumes);
        modelAndView.setViewName("index");

        return modelAndView;
    }

    @PostMapping
    public ModelAndView setConfig(DataBaseConfig config) throws Exception {

        if ("test2".equals(config.getDbname())) {
            config.setUrl("jdbc:mysql://localhost:3306/test2?characterEncoding=utf8&useSSL=false");
        } else {
            config.setUrl("jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false");
        }

        configServer.setDataBaseConfig(config);
        return new ModelAndView("redirect:/config");
    }
}
